<?php
declare (strict_types=1);

namespace app\service\logic\common\user;

use app\model\communal\UserCoinModel;
use app\model\communal\UserStatisticsModel;
use app\service\logic\BaseService;
use think\facade\Db;

final class CoinService extends BaseService
{
    protected string $modelClassName = 'UserCoinModel';

    /**
     * 返币/退款操作
     *
     * @param $params
     * @return mixed|void
     */
    public function back($params)
    {
        if ($params['coin_count'] <= 0) {
            return ;
        }

        // 获取当前用户元心币总量
        $userStaModel = UserStatisticsModel::where('user_id', $params['user_id'])->findOrEmpty();
        Db::connect('communal')->transaction(function () use ($params, $userStaModel, &$model) {
            if ($userStaModel->isEmpty()) {
                $accrueCoin = $coinCount = $coinAvailableCount = $params['coin_count'];
            } else {
                $coinCount = bcadd((string)$params['coin_count'], (string)$userStaModel['coin_count'], 2);
                $accrueCoin = bcadd((string)$params['coin_count'], (string)$userStaModel['accrue_coin'], 2);
                $coinAvailableCount = bcadd((string)$params['coin_count'], (string)$userStaModel['coin_available_count'], 2);
            }

            if (isset($params['type']) && $params['type'] == 1) {
                // 返币操作
                $userStaModel->save(['user_id' => $params['user_id'], 'accrue_coin' => $accrueCoin, 'coin_count' => $coinCount, 'coin_available_count' => $coinAvailableCount]);
            } else {
                // 其他 不累积元心币
                $userStaModel->save(['user_id' => $params['user_id'], 'coin_count' => $coinCount, 'coin_available_count' => $coinAvailableCount]);
            }

            $params['coin_balance'] = $coinCount;
            $model = UserCoinModel::create($params);
        });
    }

    /**
     * @param $type
     * @return string
     */
    public function getTypeMap($type)
    {
        $typeMap = [1 => '返币', 2 => '消费', 3 => '提现', 4 => '退款'];
        return $typeMap[$type];
    }
}
